package main

import (
	"database/sql"
	"fmt"
	"github.com/yourusername/gox/pkg/runtime"
	"strings"
	"time"
)

type User struct {
	ID        int
	Name      string
	Email     string
	Status    string
	CreatedAt time.Time
}

// 示例1: 使用简单赋值方式设置返回值
func GetActiveUsers(db *sql.DB, includeInactive bool) ([]*User, error) {
	query := func() *runtime.Query {
		__gox_sql_4_builder := runtime.NewQueryBuilder()
		__gox_sql_4_builder.AddText("SELECT * FROM users WHERE 1=1")
		__gox_sql_4_builder.AddText(fmt.Sprintf("%v", func() (result interface{}) {
			if includeInactive {
				result = "AND (status = 'active' OR status = 'inactive')"
			} else {
				result = "AND status = 'active'"
			}
			return result
		}()))
		__gox_sql_4_builder.AddText("ORDER BY created_at DESC")
		__gox_sql_4 := __gox_sql_4_builder.Build()
		return __gox_sql_4
	}()

	rows, err := db.Query(query.String(), query.Args()...)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var users []*User
	for rows.Next() {
		var user User
		err := rows.Scan(&user.ID, &user.Name, &user.Email, &user.Status, &user.CreatedAt)
		if err != nil {
			return nil, err
		}
		users = append(users, &user)
	}

	return users, nil
}

// 示例2: 在不同分支中设置不同的返回值
func GetUsersByRole(db *sql.DB, userRole string, filterByTeam bool, teamID int) ([]*User, error) {
	query := func() *runtime.Query {
		__gox_sql_3_builder := runtime.NewQueryBuilder()
		__gox_sql_3_builder.AddText("SELECT u.id, u.name, u.email, u.status, u.created_at FROM users u")
		__gox_sql_3_builder.AddText(fmt.Sprintf("%v", func() (result interface{}) {
			switch userRole {
			case "admin":
				result = "JOIN user_roles ur ON u.id = ur.user_id WHERE ur.role = 'admin'"
			case "manager":
				result = "JOIN user_roles ur ON u.id = ur.user_id WHERE ur.role = 'manager'"
			default:
				result = "WHERE u.role = 'user'"
			}
			return result
		}()))
		__gox_sql_3_builder.AddParam(func() (result interface{}) {
			if filterByTeam {
				result = teamID
			} else {
				result = 0
			}
			return result
		}())
		__gox_sql_3_builder.AddText(fmt.Sprintf("%v", func() (result interface{}) {
			if filterByTeam {
				result = "AND u.team_id = ?"
			}
			return result
		}()))
		__gox_sql_3_builder.AddText("ORDER BY u.created_at DESC")
		__gox_sql_3 := __gox_sql_3_builder.Build()
		return __gox_sql_3
	}()

	rows, err := db.Query(query.String(), query.Args()...)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var users []*User
	for rows.Next() {
		var user User
		err := rows.Scan(&user.ID, &user.Name, &user.Email, &user.Status, &user.CreatedAt)
		if err != nil {
			return nil, err
		}
		users = append(users, &user)
	}

	return users, nil
}

// 示例3: 使用循环和条件构建复杂查询
func SearchUsersDynamic(db *sql.DB, filters map[string]interface{}) ([]*User, error) {
	query := func() *runtime.Query {
		__gox_sql_2_builder := runtime.NewQueryBuilder()
		__gox_sql_2_builder.AddText("SELECT * FROM users WHERE 1=1")
		__gox_sql_2_builder.AddText(fmt.Sprintf("%v", func() (result interface{}) {
			var conditions []string
			for field, value := range filters {
				switch field {
				case "name":
					if value != "" {
						conditions = append(conditions, "AND name LIKE ?")
					}
				case "email":
					if value != "" {
						conditions = append(conditions, "AND email = ?")
					}
				case "status":
					conditions = append(conditions, "AND status = ?")
				case "min_age":
					conditions = append(conditions, "AND age >= ?")
				}
			}
			result = strings.Join(conditions, " ")
			return result
		}()))
		__gox_sql_2_builder.AddText("ORDER BY created_at DESC LIMIT")
		__gox_sql_2_builder.AddParam(func() (result interface{}) {
			if limit, ok := filters["limit"].(int); ok && limit > 0 {
				result = limit
			} else {
				result = 50
			}
			return result
		}())
		__gox_sql_2 := __gox_sql_2_builder.Build()
		return __gox_sql_2
	}()

	// 构建参数数组
	var args []interface{}
	args = append(args, query.Args()...)

	for field, value := range filters {
		switch field {
		case "name":
			if value != "" {
				args = append(args, "%"+value.(string)+"%")
			}
		case "email", "status", "min_age":
			if value != "" {
				args = append(args, value)
			}
		}
	}

	rows, err := db.Query(query.String(), args...)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var users []*User
	for rows.Next() {
		var user User
		err := rows.Scan(&user.ID, &user.Name, &user.Email, &user.Status, &user.CreatedAt)
		if err != nil {
			return nil, err
		}
		users = append(users, &user)
	}

	return users, nil
}

// 示例4: 不设置返回值的情况（使用默认零值）
func GetAllUsers(db *sql.DB, includeDeleted bool) ([]*User, error) {
	query := func() *runtime.Query {
		__gox_sql_1_builder := runtime.NewQueryBuilder()
		__gox_sql_1_builder.AddText("SELECT * FROM users WHERE 1=1")
		__gox_sql_1_builder.AddText(fmt.Sprintf("%v", func() (result interface{}) {

			if includeDeleted {

				result = "AND deleted_at IS NULL"
			}
			return result
		}()))
		__gox_sql_1_builder.AddText("ORDER BY created_at DESC")
		__gox_sql_1 := __gox_sql_1_builder.Build()
		return __gox_sql_1
	}()

	rows, err := db.Query(query.String(), query.Args()...)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var users []*User
	for rows.Next() {
		var user User
		err := rows.Scan(&user.ID, &user.Name, &user.Email, &user.Status, &user.CreatedAt)
		if err != nil {
			return nil, err
		}
		users = append(users, &user)
	}

	return users, nil
}

// 示例5: 复杂计算返回值
func GetUserStats(db *sql.DB, days int, groupBy string) ([]*User, error) {
	query := func() *runtime.Query {
		__gox_sql_0_builder := runtime.NewQueryBuilder()
		__gox_sql_0_builder.AddText("SELECT")
		__gox_sql_0_builder.AddText(fmt.Sprintf("%v", func() (result interface{}) {
			var fields []string
			if groupBy == "date" {
				fields = append(fields, "DATE(created_at) as date")
			}
			if groupBy == "status" {
				fields = append(fields, "status")
			}
			fields = append(fields, "COUNT(*) as count")
			result = strings.Join(fields, ", ")
			return result
		}()))
		__gox_sql_0_builder.AddText("FROM users WHERE created_at >=")
		__gox_sql_0_builder.AddParam(func() (result interface{}) {

			targetDate := time.Now().AddDate(0, 0, -days)
			result = targetDate.Format("2006-01-02")
			return result
		}())
		__gox_sql_0_builder.AddText(fmt.Sprintf("%v", func() (result interface{}) {
			if groupBy != "" {
				result = "GROUP BY " + groupBy
			}
			return result
		}()))
		__gox_sql_0_builder.AddText("ORDER BY created_at DESC")
		__gox_sql_0 := __gox_sql_0_builder.Build()
		return __gox_sql_0
	}()

	rows, err := db.Query(query.String(), query.Args()...)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var users []*User
	for rows.Next() {
		var user User
		err := rows.Scan(&user.ID, &user.Name, &user.Email, &user.Status, &user.CreatedAt)
		if err != nil {
			return nil, err
		}
		users = append(users, &user)
	}

	return users, nil
}

func main() {
	fmt.Println("GoX 命名返回值示例程序")
	fmt.Println("- 使用 result 变量设置返回值")
	fmt.Println("- 不设置时自动使用零值")
	fmt.Println("- 简化了代码生成逻辑")
}
